表单内容xu'yao<template>
  <div class="register-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      @submit.prevent="handleSubmit"
    >
      <!-- 手机号输入 -->
      <el-form-item prop="phone">
        <el-input
          v-model="form.phone"
          :placeholder="$t('auth.enterPhoneNumber')"
          prefix-icon="Phone"
          size="large"
          clearable
        />
      </el-form-item>

      <!-- 账号名输入 -->
      <el-form-item prop="accountName">
        <el-input
          v-model="form.accountName"
          :placeholder="$t('auth.enterAccountName')"
          prefix-icon="User"
          size="large"
          clearable
        />
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="verificationCode">
        <div class="verification-code-input">
          <el-input
            v-model="form.verificationCode"
            :placeholder="$t('auth.enterVerificationCode')"
            prefix-icon="Key"
            size="large"
            clearable
          />
          <el-button
            :disabled="cooldown > 0"
            @click="handleSendVerificationCode"
            :loading="sendingCode"
            size="large"
          >
            {{ cooldown > 0 ? `${cooldown}s` : $t('auth.getCode') }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 密码输入 -->
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          type="password"
          :placeholder="$t('auth.enterPassword')"
          prefix-icon="Lock"
          show-password
          size="large"
          clearable
        />
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          :placeholder="$t('auth.enterConfirmPassword')"
          prefix-icon="Lock"
          show-password
          size="large"
          clearable
        />
      </el-form-item>

      <!-- 用户协议 -->
      <el-form-item prop="agreement">
        <el-checkbox v-model="form.agreement">
          {{ $t('auth.agreeToTerms') }}
          <el-button link @click="openTermsDialog('terms')">
            {{ $t('auth.termsOfService') }}
          </el-button>
          {{ $t('auth.and') }}
          <el-button link @click="openTermsDialog('privacy')">
            {{ $t('auth.privacyPolicy') }}
          </el-button>
        </el-checkbox>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          :loading="loading"
          class="submit-btn"
        >
          {{ $t('auth.register') }}
        </el-button>
      </el-form-item>

      <!-- 登录链接 -->
      <div class="login-link">
        {{ $t('auth.haveAccount') }}
        <el-button link @click="$emit('switch-mode')">
          {{ $t('auth.loginNow') }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
// import { Phone, Key, Lock } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user';

const emit = defineEmits(['switch-mode', 'open-terms','update:modelValue']);
const userStore = useUserStore();
const formRef = ref<FormInstance>();
const loading = ref(false);
const sendingCode = ref(false);
const cooldown = ref(0);

// 表单数据
const form = reactive({
  phone: '',
  accountName: '',
  verificationCode: '',
  password: '',
  confirmPassword: '',
  agreement: false
});

// 表单验证规则
const rules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  accountName: [
    { required: true, message: '请输入账号名', trigger: 'blur' },
    { min: 3, max: 20, message: '账号名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入的密码不一致'));
          console.log(rule);
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        console.log(rule);
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 发送验证码
const handleSendVerificationCode = async () => {
  // 验证手机号
  try {
    await formRef.value?.validateField('phone');
    
    sendingCode.value = true;
    
    try {
      await userStore.sendVerificationCode(form.phone);
      ElMessage.success('验证码已发送，请注意查收');
      
      // 开始倒计时
      cooldown.value = 60;
      const timer = setInterval(() => {
        cooldown.value--;
        if (cooldown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } catch (error: any) {
      ElMessage.error(error.message || '验证码发送失败，请稍后重试');
    } finally {
      sendingCode.value = false;
    }
  } catch (error) {
    // 手机号验证失败
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      try {
        await userStore.register({
          phone: form.phone,
          accountName: form.accountName,
          verificationCode: form.verificationCode,
          password: form.password
        });
        
        ElMessage.success('注册成功，已自动登录');
        
        // 关闭弹窗 (通过父组件的v-model实现)
        emit('update:modelValue', false);
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 打开条款弹窗
const openTermsDialog = (type: string) => {
  emit('open-terms', type);
};
</script>

<style scoped lang="scss">
.register-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;  // 减小表单项之间的间距
  }

  .verification-code-input {
    display: flex;
    gap: 10px;
    
    .el-input {
      flex: 1;
    }
    
    .el-button {
      width: 100px;
      height: 40px;  // 与输入框高度一致
    }
  }
  
  // 用户协议复选框左侧对齐
  :deep(.el-form-item:has(.el-checkbox)) {
    margin-left: 0;
    margin-bottom: 22px;
  }
  
  :deep(.el-checkbox__label) {
    color: #606266;
  }
  
  .submit-btn {
    width: 100%;
    height: 40px;  // 增加按钮高度
    font-size: 16px;  // 增大按钮文字
  }
  
  .login-link {
    text-align: center;
    margin-top: 16px;
    color: #606266;
    font-size: 14px;

    .el-button {
      padding: 0 4px;
      font-size: 14px;
      font-weight: 500;
    }
  }
}
</style>